//
//  UITableView+MC.m
//  eCook
//
//  Created by 曹飞 on 2017/9/27.
//

#import "UITableView+MC.h"
#import <objc/runtime.h>

static void MCExchangedMethod(SEL originalSelector, SEL swizzledSelector, Class class) {
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    BOOL didAddMethod =
    class_addMethod(class,
                    originalSelector,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    }
    else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

@implementation UITableView (MC)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL selectors[] = {
            @selector(initWithCoder:),
            @selector(initWithFrame:style:),
        };
        
        for (NSUInteger index = 0; index < sizeof(selectors)/ sizeof(SEL); ++index) {
            SEL originalSelector = selectors[index];
            SEL swizzledSelector = NSSelectorFromString([@"mc_" stringByAppendingString:NSStringFromSelector(originalSelector)]);
            
            Class class = [self class];
            MCExchangedMethod(originalSelector, swizzledSelector, class);
        }
    });
}

- (id)mc_initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    if (self == [self mc_initWithFrame:frame style:style]) {
        [self setGlobalPropertyForIOS11];
    }
    return self;
}

- (id)mc_initWithCoder:(NSCoder *)aDecoder {
    if (self == [self mc_initWithCoder:aDecoder]) {
        [self setGlobalPropertyForIOS11];
    }
    return self;
}

- (void)setGlobalPropertyForIOS11 {
    /**
     * iOS11, tableview自动开启estimatedHeight, iOS11以下系统,下列Api默认=0, 现在默认是UITableViewAutomaticDimension
     * 重新设成0关闭自动估算高度
     */
    self.estimatedRowHeight = 0;
    self.estimatedSectionHeaderHeight = 0;
    self.estimatedSectionFooterHeight = 0;
}

@end

